import java.text.DecimalFormat;

import com.aliyun.odps.udf.UDF;
import com.aliyun.odps.utils.StringUtils;

public class GoodsSamePartPer extends UDF {
	
	/*
	 * public static void main(String[] args) { String brand = "Elizabeth Arden";
	 * String aUrl =
	 * "https://www.beautyexpert.com/elizabeth-arden-flawless-finish-porcelain-beige/10043879.html";
	 * String aTitle = "Elizabeth Arden - Flawless Finish Porcelain Beige"; String
	 * bUrl =
	 * "https://www.beautyexpert.com/elizabeth-arden-flawless-finish-gentle-beige/10043881.html";
	 * String bTitle = "Elizabeth Arden - Flawless Finish Gentle Beige";
	 * System.out.println(evaluate(brand, aUrl, aTitle, bUrl, bTitle)); }
	 */

	/**
	 * 查找出相似度百分比
	 * 
	 * @param brand
	 * @param aUrl
	 * @param aTitle
	 * @param bUrl
	 * @param bTitle
	 * @return
	 */
	public Double evaluate(String brand, String aUrl, String aTitle, String bUrl, String bTitle) {
		try {
			// 同一商品不做比较
			if (StringUtils.equals(aTitle, bTitle)) {
				return null;
			}
			// 替换title中的brand
			aTitle = aTitle.replace(brand, "");
			bTitle = bTitle.replace(brand, "");
			System.out.println(aTitle + "----------" + bTitle);
			// 不同商品将title转成大写，除去空格，切成数组
			String[] aArr = aTitle.toUpperCase().replace(" ", "").split("");
			String[] bArr = bTitle.toUpperCase().replace(" ", "").split("");

			// 获取短数组的长度
			int minArrLength = aArr.length > bArr.length ? bArr.length : aArr.length;
			StringBuffer sb = new StringBuffer();

			// 循环
			for (int i = 0; i < minArrLength; i++) {
				if (!StringUtils.equals(aArr[i], bArr[i])) {
					break;
				}
				sb.append(aArr[i]);
			}

			// 相似部分
			String samePart = sb.toString();
			System.out.println(samePart);
			//获取并集
			String comePart = aTitle.toUpperCase().replace(" ", "").replace(samePart, "")
					+bTitle.toUpperCase().replace(" ", "");
			System.out.println(comePart);
			if (StringUtils.isBlank(samePart)) {
				// 为空 相似度为0
				return 0.00;
			} else {
				int sameLength = samePart.length();
				DecimalFormat decimalFormat = new DecimalFormat(".00");
				String format = decimalFormat.format(Double.valueOf(sameLength) / Double.valueOf(comePart.length()));
				Double per = Double.valueOf(format);
				System.out.println(per + "---------");
				return per;
			}
		} catch (Exception e) {
			return 0.8;
		}

	}
}
